<template>
  <div class="orderMsg">
    <div class="introduction">
      <div class="list">
        <div>商户全称：{{ merchOption.merchName }}</div>
        <div>联系电话：{{ merchOption.merchPhone }}</div>
      </div>
      <div class="list">商户总部地址：{{ merchOption.address }}</div>
      <div class="list">
        出资方：
        <span style="color: #ffb72f">{{
          merchOption.stakeValue == 1 ? "本商户" : "合作商户"
        }}</span>
      </div>
      <div class="list">
        状态：
        <span style="color: #ffb72f">{{
          merchOption.exParty == 0 ? "合作中" : "已退出"
        }}</span>
      </div>
    </div>

    <el-tabs v-model="activeName" class="table_box" @tab-click="handleClick">
      <el-tab-pane label="返佣" name="first">
        <div class="combined">
          <div class="list">
            <div style="overflow: hidden">
              <h2 style="float: left">订单量</h2>
              <el-tooltip
                popper-class="el-tooltip-theme-fresh"
                placement="top"
                effect="light"
              >
                <div slot="content">订单数统计未全部售后的订单</div>
                <i class="el-icon-question" />
              </el-tooltip>
            </div>

            <p>{{ tableData.orderCount }}单</p>
          </div>
          <div class="list">
            <div style="overflow: hidden">
              <h2 style="float: left">佣金</h2>
              <el-tooltip
                popper-class="el-tooltip-theme-fresh"
                placement="top"
                effect="light"
              >
                <div slot="content">
                  <p>1.支付方式为“商户会员余额”将不产生佣金；</p>
                  <p>2.当订单支付金额低于100元也将不产生佣金；</p>
                  <p>3.订单售后将扣减对应佣金；</p>
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </div>
            <p>{{ tableData.totalCommission }}元</p>
          </div>
        </div>

        <!-- 筛选条件 -->
        <div class="searchMenber">
          <el-form ref="filterForm" inline size="small">
            <el-form-item style="width: 12%">
              <el-input
                v-model.trim="filterForm.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="filterForm.orderNo"
                placeholder="请输入订单号"
              />
            </el-form-item>
            <!-- <el-form-item style="width: 12%">
              <el-autocomplete
                v-model.trim="filterForm.memberName"
                placeholder="请输入昵称关键字"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearch"
                hide-loading
                @clear="setBlur()"
                @select="selectName"
              />
            </el-form-item> -->
            <el-form-item style="width: 12%">
              <el-select
                v-model="filterForm.shopName"
                placeholder="请选择门店"
                @change="selectShop"
              >
                <el-option
                  v-for="item in shopList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="width: 12%">
              <el-select
                v-model="filterForm.favourableType"
                placeholder="请选择优惠类型"
              >
                <el-option
                  v-for="item in selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="width: 12%">
              <el-select
                v-model="filterForm.orderTradeType"
                placeholder="请选择订单类型"
              >
                <el-option
                  v-for="item in orderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="width: 22%">
              <el-date-picker
                v-model="filterForm.timeRange"
                :clearable="false"
                align="center"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="~"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                @change="limitTime"
              />
            </el-form-item>
            <el-form-item>
              <template>
                <el-button type="primary" @click="searchFn">搜索</el-button>
                <el-button @click="reset">重置</el-button>
                <el-button type="primary" @click="downExcel()">导出</el-button>
              </template>
            </el-form-item>
          </el-form>
        </div>
        <!-- 筛选条件 -->

        <!-- 表格 -->
        <div class="table_box">
          <el-table
            :data="tableData"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            border
            style="width: 100%"
          >
            <el-table-column prop="userName" label="用户昵称" />
            <el-table-column prop="userPhone" label="手机号" />
            <el-table-column prop="orderId" label="订单号" />
            <el-table-column prop="shopName" label="门店" />
            <el-table-column prop="orderAmount" label="订单总额(元)" />
            <el-table-column prop="payAmount" label="支付总额(元)" />
            <el-table-column prop="payType" label="支付方式" />
            <el-table-column prop="preferType" label="优惠类型">
              <template slot-scope="scope">
                <p>{{ scope.row.preferType }}</p>
                <p>{{ scope.row.bizDesc }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="prefer" label="优惠" />
            <el-table-column prop="payTime" label="支付时间" />
            <el-table-column prop="commissionRatio" label="抽佣比例" />
            <!-- <el-table-column prop="bookedRatio" label="实际入账比例" /> -->
            <el-table-column prop="commission" label="佣金(元)">
              <template slot="header" slot-scope="scope">
                <span>佣金(元)</span>
                <el-tooltip
                  popper-class="el-tooltip-theme-fresh"
                  placement="top"
                  effect="light"
                >
                  <div slot="content">
                    <p>
                      佣金 = （支付总额 - 交易手续费）* 抽佣比例 *
                      实际入账比例；
                    </p>
                    <p>
                      例：110元实付，交易手续费10元，抽佣比例5%，实际入账比例70%；
                    </p>
                    <p>100 * 0.05 * 0.7 = 3.5元；</p>
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <p
                  :style="{
                    color: scope.row.orderType == 1 ? 'red' : 'skyblue',
                  }"
                >
                  {{ scope.row.commission }}
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="orderType" label="订单类型">
              <template slot-scope="scope">
                <p>{{ scope.row.orderType == 1 ? "交易订单" : "售后订单" }}</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <el-tab-pane label="补贴" name="second">
        <div class="combined">
          <div class="list">
            <div style="overflow: hidden">
              <h2 style="float: left">订单量</h2>
              <el-tooltip
                popper-class="el-tooltip-theme-fresh"
                placement="top"
                effect="light"
              >
                <div slot="content">订单数统计未全部售后的订单</div>
                <i class="el-icon-question" />
              </el-tooltip>
            </div>
            <p>{{ tableData.totalOrder }}单</p>
          </div>
          <div class="list">
            <div style="overflow: hidden">
              <h2 style="float: left">补贴</h2>
              <el-tooltip
                popper-class="el-tooltip-theme-fresh"
                placement="top"
                effect="light"
              >
                <div slot="content">订单在有效期内售后，补贴金额将自动返回</div>
                <i class="el-icon-question" />
              </el-tooltip>
            </div>
            <p>{{ tableData.totalSubsidy }}元</p>
          </div>
        </div>
        <!-- 筛选条件 -->
        <div class="searchMenber">
          <el-form ref="filterForm" inline size="small">
            <el-form-item style="width: 12%">
              <el-input
                v-model.trim="filterForm.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="filterForm.orderNo"
                placeholder="请输入订单号"
              />
            </el-form-item>
            <!-- <el-form-item style="width: 12%">
              <el-autocomplete
                v-model.trim="filterForm.memberName"
                placeholder="请输入昵称关键字"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearch"
                hide-loading
                @clear="setBlur()"
                @select="selectName"
              />
            </el-form-item> -->
            <el-form-item style="width: 12%">
              <el-select
                v-model="filterForm.shopName"
                placeholder="请选择门店"
                @change="selectShop"
              >
                <el-option
                  v-for="item in shopList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="width: 12%">
              <el-select
                v-model="filterForm.favourableType"
                placeholder="请选择补贴方式"
              >
                <el-option
                  v-for="item in selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="width: 12%">
              <el-select
                v-model="filterForm.orderTradeType"
                placeholder="请选择订单类型"
              >
                <el-option
                  v-for="item in orderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="width: 22%">
              <el-date-picker
                v-model="filterForm.timeRange"
                :clearable="false"
                align="center"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="~"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                @change="limitTime"
              />
            </el-form-item>
            <el-form-item>
              <template>
                <el-button type="primary" @click="searchFn">搜索</el-button>
                <el-button @click="reset">重置</el-button>
                <el-button type="primary" @click="downExcel()">导出</el-button>
              </template>
            </el-form-item>
          </el-form>
        </div>
        <!-- 筛选条件 -->

        <!-- 表格 -->
        <div class="table_box">
          <el-table
            :data="tableData"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            border
            style="width: 100%"
          >
            <el-table-column prop="userName" label="用户昵称" />
            <el-table-column prop="userPhone" label="手机号" />
            <el-table-column prop="orderId" label="订单号" />
            <el-table-column prop="shopName" label="门店" />
            <el-table-column prop="orderAmount" label="订单总额(元)" />
            <!-- <el-table-column prop="payAmount" label="支付总和(元)" /> -->
            <el-table-column prop="butieType" label="补贴方式">
              <template slot-scope="scope">
                <p>{{ scope.row.butieType }}</p>
                <p>{{ scope.row.bizDesc }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="prefer" label="优惠" />
            <el-table-column prop="preferMoney" label="优惠金额(元)" />
            <!-- <el-table-column prop="payType" label="支付方式" /> -->
            <!-- <el-table-column prop="discount" label="折扣" /> -->
            <el-table-column prop="payTime" label="支付时间" />
            <el-table-column prop="butieMoney" label="补贴金额(元)">
              <template slot-scope="scope">
                <p
                  :style="{
                    color: scope.row.orderType == 1 ? 'red' : 'skyblue',
                  }"
                >
                  {{ scope.row.butieMoney }}
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="orderType" label="订单类型">
              <template slot-scope="scope">
                <p>{{ scope.row.orderType == 1 ? "交易订单" : "售后订单" }}</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <pag-ination
      :page-total="pagTotal"
      :watch-curpage="conditions.pageNum"
      @pageNum="getPageNum"
      @pageSize="getPageSize"
    />
  </div>
</template>

<script>
import pagInation from '../../components/pagInation/index.vue'
import {
  participantQueryMemberOrder,
  queryOrderSubsidyDetails,
  getShopList
} from '@/api/business'
import { downCoreMerSubsidy, downCoreMerCommission } from '@/api/download'
export default {
  components: {
    'pag-ination': pagInation
  },
  data() {
    return {
      filterForm: {
        phone: '',
        orderNo: '',
        memberName: '',
        memberId: null,
        shopId: null,
        shopName: '',
        favourableType: '',
        orderTradeType: '',
        butieType: '',
        timeRange: [
          this.$momentMini().subtract(90, 'days').format('YYYY-MM-DD') +
            ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        beginTime: '',
        endTime: ''
      }, // 筛选内容

      // 优惠类型配置
      selectOptions: [
        {
          value: 1,
          label: '超级会员折扣'
        },
        {
          value: 2,
          label: '优惠券'
        },
        {
          value: 3,
          label: '超级会员积分'
        },
        {
          value: 4,
          label: '会员日'
        },
        {
          value: 5,
          label: '会员卡'
        },
        {
          value: 6,
          label: '会员生日'
        }
      ],
      // 订单类型配置
      orderOptions: [
        {
          value: 1,
          label: '交易订单'
        },
        {
          value: 2,
          label: '售后订单'
        }
      ],
      merchOption: '',

      /* 查询 */
      conditions: {
        merchName: '',
        merchPhone: '',
        pageNum: 1,
        pageSize: 10
      },
      pagTotal: null,
      // tab
      activeName: 'first',
      /* 表格 */
      tableData: [
        {
          userName: '',
          userPhone: '',
          orderId: '',
          shopName: '',
          orderAmount: '',
          payAmount: '',
          butieType: '', // 积分 优惠券
          payType: null,
          preferType: '', // 超级会员折扣 //优惠券
          prefer: '', // 满100元减20元
          preferMoney: '',
          payTime: '',
          commissionRatio: '',
          bookedRatio: '',
          commission: '',
          orderType: '' // 订单售后
        }
      ],
      nameList: [],
      nameArr: [],
      shopList: []
    }
  },
  mounted() {
    this.merchOption = JSON.parse(this.$route.query.merchOption)
    this.queryMemberOrderFun()
    this.getShopList()
  },
  methods: {
    // 获取分页
    getPageNum(val) {
      this.conditions.pageNum = val
      this.queryMemberOrderFun()
    },
    getPageSize(val) {
      this.conditions.pageSize = val
      this.queryMemberOrderFun()
    },

    // 请求订单信息
    queryMemberOrderFun() {
      const { businessId, id } = this.merchOption
      const form = {
        businessId,
        superBusinessId: businessId,
        pageNum: this.conditions.pageNum,
        pageSize: this.conditions.pageSize
      }
      if (this.activeName == 'first') {
        this.queryMemberOrderApi(form)
      } else {
        this.queryInviterSubsidyOrderApi(form)
      }
    },
    queryMemberOrderApi(form) {
      const pageNum = this.conditions.pageNum
      const pageSize = this.conditions.pageSize
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = this.fetchFilterParams()
      participantQueryMemberOrder({ ...form, ...params }).then((res) => {
        if (res.code == 0) {
          const data = res.data.list
          const tableData = []
          data.forEach((el) => {
            const dataItem = {
              userName: el.memberName,
              userPhone: el.mobilePhone,
              orderId: el.orderNo,
              shopName: el.shopName,
              orderAmount: el.totalFee / 100,

              payAmount: el.ssFee / 100,
              payType: el.payType,
              preferType:
                el.favourableType == 1
                  ? '超级会员折扣'
                  : el.favourableType == 2
                    ? '优惠券'
                    : el.favourableType == 3
                      ? '超级会员积分'
                      : el.favourableType == 4
                        ? '会员日折扣'
                        : el.favourableType == 5
                          ? '会员卡折扣'
                          : el.favourableType == 6
                            ? '会员生日折扣'
                            : '',
              bizDesc: el.bizDesc,
              prefer: el.discountDesc,
              payTime: el.payTime,
              commissionRatio: el.rakeRate + '%',
              bookedRatio: el.actualFeeRate + '%',
              commission: el.commissionFee / 100,
              orderType: el.orderTradeType
            }
            tableData.push(dataItem)
          })
          this.tableData = tableData
          this.pagTotal = res.data.total
          this.tableData.orderCount = res.data.orderCount
          this.tableData.totalCommission = res.data.totalCommission / 100
        }
      })
    },
    queryInviterSubsidyOrderApi(form) {
      const pageNum = this.conditions.pageNum
      const pageSize = this.conditions.pageSize
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = this.fetchFilterParams()
      queryOrderSubsidyDetails({ ...form, ...params }).then((res) => {
        // console.log("请求补贴订单", res);
        if (res.code == 0) {
          const data = res.data.list
          const tableData = []
          data.forEach((el) => {
            const dataItem = {
              userName: el.memberName,
              userPhone: el.mobilePhone,
              orderId: el.orderNo,
              shopName: el.shopName,
              orderAmount: el.totalFee / 100,
              butieType:
                el.favourableType == 1
                  ? '超级会员折扣'
                  : el.favourableType == 2
                    ? '优惠券'
                    : el.favourableType == 3
                      ? '超级会员积分'
                      : el.favourableType == 4
                        ? '会员日折扣'
                        : el.favourableType == 5
                          ? '会员卡折扣'
                          : el.favourableType == 6
                            ? '会员生日折扣'
                            : '',
              bizDesc: el.bizDesc,
              // payAmount: el.ssFee / 100,
              // payType: el.payType,
              // preferType: el.favourableType == 1 ? '超级会员折扣' : el.favourableType == 2 ? '优惠券' : '积分',
              prefer: el.discountDesc,
              preferMoney: el.discountFee / 100,
              payTime: el.payTime,
              butieMoney: el.subsidyAmount / 100,
              // commissionRatio: el.rakeRate + '%',
              // bookedRatio: el.actualFeeRate + '%',
              // commission: el.commissionFee / 100,
              orderType: el.orderTradeType
            }
            tableData.push(dataItem)
          })
          this.tableData = tableData
          this.pagTotal = res.data.total
          this.tableData.orderCount = res.data.total
          this.tableData.totalSubsidy = res.data.totalSubsidy / 100
          this.tableData.totalOrder = res.data.totalOrder
        }
      })
    },

    // tab
    handleClick(tab, event) {
      this.conditions.pageNum = 1
      this.filterForm = {
        timeRange: [
          this.$momentMini().subtract(90, 'days').format('YYYY-MM-DD') +
            ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ]
      }
      this.queryMemberOrderFun()
    },

    // 获取门店
    async getShopList() {
      try {
        const res = await getShopList()
        this.shopList = res.data
      } catch (error) {
        console.log('获取门店', error)
      }
    },

    // 搜索时间限制3个月
    limitTime(val) {
      this.filterForm.beginTime = val[0]
      this.filterForm.endTime = val[1]
      // 获取3个月的时间
      const three = 3 * 30 * 24 * 3600 * 1000
      // 选择的开始时间
      const beginTime = new Date(val[0]).getTime()
      const endTime = new Date(val[1]).getTime()
      const result = endTime - beginTime
      if (result > three) {
        this.filterForm.timeRange = [
          this.$momentMini().subtract(90, 'days').format('YYYY-MM-DD') +
            ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ]
        return this.$message.error('所选时间不可超出90天')
      }
    },

    // 搜索
    searchFn() {
      this.queryMemberOrderFun()
    },

    // 重置
    reset() {
      this.filterForm = {
        phone: '',
        orderNo: '',
        memberName: '',
        shopName: '',
        favourableType: '',
        orderTradeType: '',
        timeRange: [
          this.$momentMini().subtract(90, 'days').format('YYYY-MM-DD') +
            ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        beginTime: '',
        endTime: ''
      }
      this.queryMemberOrderFun()
    },

    // 选择门店
    selectShop(id) {
      const index = this.shopList.findIndex((item) => {
        return item.id === id
      })
      this.filterForm.shopId = this.shopList[index].id
    },

    // 获取筛选参数
    fetchFilterParams() {
      const params = Object.assign({}, this.filterForm)

      if (params.timeRange) {
        params.beginTime = params.timeRange[0]
        params.endTime = params.timeRange[1]
      }

      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }

      return params
    },

    // 导出
    downExcel() {
      const { businessId } = this.merchOption
      const data = this.fetchFilterParams()
      console.log('data713', data)
      if (this.activeName == 'first') {
        downCoreMerCommission({ ...data, joinBusinessId: businessId }).then(
          (res) => {
            if (res.code === 0) {
              this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
                confirmButtonText: '确定',
                center: true,
                type: 'success'
              })
            }
          }
        )
      } else {
        downCoreMerSubsidy({ ...data, joinBusinessId: businessId }).then(
          (res) => {
            if (res.code === 0) {
              this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
                confirmButtonText: '确定',
                center: true,
                type: 'success'
              })
            }
          }
        )
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.orderMsg {
  .introduction {
    overflow: hidden;
    background-color: white;
    padding: 0 20px;
    .list {
      width: 100%;
      overflow: hidden;
      margin: 20px 0;
      div {
        float: left;
        margin-right: 50px;
      }
    }
  }
  .combined {
    width: 100%;
    overflow: hidden;
    background-color: white;
    padding: 16px;
    padding-bottom: 0;
    margin-top: 8px;
    .list {
      float: left;
      background-color: #fcf6eb;
      margin-right: 8px;
      padding: 8px;
      // color: white;
      text-align: center;
      h2 {
        font-weight: bold;
        font-size: 18px;
      }
    }
  }
  .searchMenber {
    margin-top: 20px;
    padding-left: 16px;
    .el-button {
      padding: 10px 22px;
    }
  }
  .table_box {
    width: 100%;
    overflow: hidden;
    padding: 20px;
    background-color: white;
  }
}
</style>
